﻿
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;

using FreeSql;
using Kalman;
using Newtonsoft.Json.Linq;

namespace QuDao
{
    /// <summary>
    /// 租户账户业务对象（处理数据表base_tenant_account相关的业务逻辑）
    /// </summary>
    public sealed partial class TenantAccountBO : SingletonBase<TenantAccountBO>
    {
        readonly IFreeSql fsql;
        public TenantAccountBO() : base()
        {
            fsql = ServiceLocator.Instance.GetRequiredService<IFreeSql>();
        }
        
        /// <summary>
        /// 获取租户账户
        /// </summary>
        /// <param name="id">主键ID的值</param>
        /// <returns></returns>
        public T GetItem<T>(int id)
        {
        	if (id <= 0) return default;
            var item = fsql.Select<TenantAccount>().Where(a => a.ID == id).ToOne<T>();
            return item;
        }
        
        public TenantAccount GetItem(int id)
        {
        	return GetItem<TenantAccount>(id);
        }
        
        /// <summary>
        /// 获取租户银行账户数据列表
        /// </summary>
        /// <param name="tid">租户ID</param>
        /// <returns></returns>
        public List<TenantAccountDto> GetList(int tid)
        {
            var list = fsql.Select<TenantAccount>().Where(a => a.TID == tid).ToList<TenantAccountDto>();
            return list;
        }
        
        /// <summary>
        /// 获取租户账户数据列表
        /// </summary>
        /// <returns></returns>
        public List<T> GetList<T>(int[] ids)
        {
        	if (ids == null || ids.Length == 0) return new List<T>();
            var list = fsql.Select<TenantAccount>().Where(a => ids.Contains(a.ID)).ToList<T>();
            return list;
        }
        
        /// <summary>
        /// 新增租户账户
        /// </summary>
        public int Add(TenantAccountAddDto dto)
        {
        	var entity = dto.CopyTo<TenantAccount>();
        	
            entity.CreateTime = DateTime.Now;
            entity.ModifyTime = DateTime.Now;
            entity.ID = (int)fsql.Insert(entity).ExecuteIdentity();
            return entity.ID;
        }

        /// <summary>
        /// 修改租户账户
        /// </summary>
        public int Modify(TenantAccountModifyDto dto)
        {
            var item = GetItem<TenantAccount>(dto.ID) ?? throw new AppException($"租户账户不存在：{dto.ID}");

            var update = fsql.Update<TenantAccount>(dto.ID).Set(a => a.ModifyTime, DateTime.Now);
            
			if (dto.BankName != item.BankName) update.Set(a => a.BankName, dto.BankName);
			if (dto.AccountName != item.AccountName) update.Set(a => a.AccountName, dto.AccountName);
			if (dto.AccountNo != item.AccountNo) update.Set(a => a.AccountNo, dto.AccountNo);
						
			return update.ExecuteAffrows();
        }

        /// <summary>
        /// 修改租户账户（根据字典数据修改）
        /// </summary>
        /// <param name="id">租户账户ID</param>
        /// <param name="dic">待修改的字典数据（KEY：字段名，Value：修改值）</param>
        public int ModifyByDic(int id, Dictionary<string, object> dic)
        {
        	if (dic == null || dic.Count == 0) throw new AppException("字典数据不能为空");
            var item = GetItem<TenantAccount>(id) ?? throw new AppException($"租户账户不存在：{id}");

            var update = fsql.Update<TenantAccount>(id).Set(a => a.ModifyTime, DateTime.Now);
            
            if (dic.ContainsKey("TID")) update.Set(a => a.TID, dic["TID"]);
			if (dic.ContainsKey("BankName")) update.Set(a => a.BankName, dic["BankName"]);
			if (dic.ContainsKey("AccountName")) update.Set(a => a.AccountName, dic["AccountName"]);
			if (dic.ContainsKey("AccountNo")) update.Set(a => a.AccountNo, dic["AccountNo"]);
						
			return update.ExecuteAffrows();
        }

        /// <summary>
        /// 修改租户账户（修改指定字段值）
        /// </summary>
        /// <param name="id">租户账户ID</param>
        /// <param name="fieldName">字段名</param>
        /// <param name="fieldValue">字段值</param>
        /// <returns></returns>
        public int ModifyByField(int id, string fieldName, object fieldValue)
        {
            var dic = new Dictionary<string, object>
            {
                { fieldName, fieldValue }
            };
            return ModifyByDic(id, dic);
        }

		/// <summary>
        /// 删除租户账户数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int[] ids)
        {
        	if (ids == null || ids.Length == 0) return 0;
        	return fsql.Delete<TenantAccount>().Where(a => ids.Contains(a.ID)).ExecuteAffrows();
        }
        
        /// <summary>
        /// 删除租户账户数据
        /// </summary>
        /// <returns>返回影响行数</returns>
        public int Delete(int id)
        {
        	return fsql.Delete<TenantAccount>(id).ExecuteAffrows();
        }
        
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="req">分页查询请求对象</param>
        public PagingResult<TenantAccount> Query(PagingRequest req, int tid = 0)
        {
        	if (req == null) throw new AppException("查询数据不能为空");
        	
            var select = fsql.Select<TenantAccount>().WhereIf(tid > 0, a => a.TID == tid);
            foreach (var item in req.FilterItems)
            {
                switch (item.Field)
                {
                    case "ID":
                        select.Where(a => a.ID == int.Parse(item.Value));
                        break;
                    //case "TenantAccountName":
                    //    select.Where(a => a.TenantAccountName.Contains(item.Value));
                    //    break;
                    default:
                        break;
                }
            }

            if (!string.IsNullOrEmpty(req.SortExp))
            {
                select.OrderBy(req.SortExp);//自定义排序
            }
            else
            {
                select.OrderByDescending(a => a.ID);//默认排序
            }

            //var sql = select.ToSql();

            var list = select.Count(out var total).Page(req.PageIndex, req.PageSize).ToList<TenantAccount>();
            return new PagingResult<TenantAccount>
            {
                PageIndex = req.PageIndex,
                PageSize = req.PageSize,
                Data = list,
                Total = (int)total
            };
        }
        
    }
}
